<template>
  <div>
    <!-- 顶部统计卡片 -->
    <div class="stats-card">
      <a-row :gutter="16">
        <a-col :span="6">
          <div class="card-item">
            <p class="card-title">今日活跃用户</p>
            <p class="card-value">{{ todayActiveUser }}</p>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="card-item">
            <p class="card-title">近7天活跃用户</p>
            <p class="card-value">{{ sevenDayActiveUser }}</p>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="card-item">
            <p class="card-title">今日认证</p>
            <p class="card-value">{{ todayCertify }}</p>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="card-item">
            <p class="card-title">今日PK</p>
            <p class="card-value">{{ todayPk }}</p>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 区县活跃度柱状图 -->
    <div class="chart-box">
      <div class="chart-header">
        <p class="chart-title">区县活跃度</p>
        <div class="chart-controls">
          <a-button
            :type="activePeriod === 'sevenDays' ? 'primary' : 'default'"
            @click="changePeriod('sevenDays')"
          >
            近7天
          </a-button>
          <a-button
            :type="activePeriod === 'month' ? 'primary' : 'default'"
            @click="changePeriod('month')"
            style="margin-left: 8px"
          >
            近30天
          </a-button>
        </div>
      </div>
      <div id="districtBarChart" style="width: 100%; height: 300px;"></div>
    </div>

    <!-- 底部列表 -->
    <a-row :gutter="16" class="list-row">
      <a-col :span="8">
        <div class="list-box">
          <div class="list-header">
            <p class="list-title">区县排行</p>
            <a-select
              v-model:value="districtPost"
              style="width: 150px"
              placeholder="选择岗位"
              @change="handlePostChange('district')"
              :loading="postsLoading"
            >
              <a-select-option value="">全部岗位</a-select-option>
              <a-select-option v-for="(label,value) in posts" :key="value" :value="value">
                {{ label }}
              </a-select-option>
            </a-select>
          </div>
          <div class="table-scroll-container">
            <a-table
              :columns="districtRankColumns"
              :data-source="districtRankData"
              :pagination="false"
              :scroll="{ y: 240 }"
              :row-key="record => record.district"
              :loading="districtRankLoading"
            ></a-table>
          </div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="list-box">
          <div class="list-header">
            <p class="list-title">个人排行</p>
            <a-select
              v-model:value="personalPost"
              style="width: 150px"
              placeholder="选择岗位"
              @change="handlePostChange('personal')"
              :loading="postsLoading"
            >
              <a-select-option value="">全部岗位</a-select-option>
              <a-select-option v-for="(label,value) in posts" :key="value" :value="value">
                {{ label }}
              </a-select-option>
            </a-select>
          </div>
          <div class="table-scroll-container">
            <a-table
              :columns="personalRankColumns"
              :data-source="personalRankData"
              :pagination="false"
              :scroll="{ y: 240 }"
              :row-key="record => record.userName + record.district"
              :loading="personalRankLoading"
            ></a-table>
          </div>
        </div>
      </a-col>
      <a-col :span="8">
        <div class="list-box">
          <p class="list-title">各区县人数</p>
          <div class="table-scroll-container">
            <a-table
              :columns="districtPeopleColumns"
              :data-source="districtPeopleData"
              :pagination="false"
              :scroll="{ y: 280 }"
              :row-key="record => record.districtName"
              :loading="districtPeopleLoading"
            ></a-table>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { req } from '../../api/axiosFun';
import * as echarts from 'echarts';

export default {
  name: 'Dashboard',
  data() {
    return {
      // 顶部统计数据
      todayActiveUser: 0,
      sevenDayActiveUser: 0,
      todayCertify: 0,
      todayPk: 0,

      // 加载状态
      statsLoading: false,
      chartLoading: false,
      districtRankLoading: false,
      personalRankLoading: false,
      districtPeopleLoading: false,
      postsLoading: false,

      // 岗位筛选相关 - 分开存储两个筛选器的值
      posts: {}, // 岗位列表（对象形式存储）
      districtPost: '', // 区县排行选中的岗位
      personalPost: '', // 个人排行选中的岗位

      // 区县排行表格列配置
      districtRankColumns: [
        {
          title: '区县',
          dataIndex: 'district',
          key: 'district',
        },
        {
          title: '积分',
          dataIndex: 'avgScore',
          key: 'avgScore',
        },
      ],
      districtRankData: [],

      // 个人排行表格列配置
      personalRankColumns: [
        {
          title: '姓名',
          dataIndex: 'userName',
          key: 'userName',
        },
        {
          title: '区县',
          dataIndex: 'district',
          key: 'district',
        },
        {
          title: '积分',
          dataIndex: 'totalScore',
          key: 'totalScore',
        },
      ],
      personalRankData: [],

      // 各区县人数表格列配置
      districtPeopleColumns: [
        {
          title: '区县',
          dataIndex: 'districtName',
          key: 'districtName',
        },
        {
          title: '人数',
          dataIndex: 'totalUsers',
          key: 'totalUsers',
        },
      ],
      districtPeopleData: [],

      // 图表数据
      barChartData: {
        xAxisData: [],
        sevenDaysData: [],  // 近7天数据
        monthData: [],      // 近30天数据
      },
      activePeriod: 'sevenDays',  // 当前激活的时间周期
      chartInstance: null,        // 图表实例
    };
  },
  mounted() {
    // 先获取岗位列表，再加载其他数据
    this.fetchPosts().then(() => {
      this.fetchAllData();
    });
    // 监听窗口大小变化，自适应图表
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.resizeChart);
    // 销毁图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    // 批量获取所有数据
    async fetchAllData() {
      try {
        const [statsRes, chartRes, districtRankRes, personalRankRes, districtPeopleRes] =
          await Promise.all([
            this.fetchStatsData(),
            this.fetchChartData(),
            this.fetchDistrictRankData(),
            this.fetchPersonalRankData(),
            this.fetchDistrictPeopleData()
          ]);

        this.processStatsResponse(statsRes);
        this.processChartResponse(chartRes);
        this.processDistrictRankResponse(districtRankRes);
        this.processPersonalRankResponse(personalRankRes);
        this.processDistrictPeopleResponse(districtPeopleRes);

        this.initBarChart();
      } catch (error) {
        console.error('获取数据失败：', error);
        this.$message.error('获取数据失败，请稍后重试');
      }
    },

    // 获取岗位列表
    async fetchPosts() {
      this.postsLoading = true;
      try {
        const res = await req('post', '/dict/getDictItemByNo', { dicNo: 'position' });
        if (res.result === 'success') {
          const dictMap = {};
          res.data.forEach((item) => {
            dictMap[item.dicValue.toString()] = item.dicDisplayName;
          });
          this.posts = dictMap;
          return Promise.resolve();
        } else {
          this.$message.error(res.message || '获取岗位列表失败');
          return Promise.reject(res.message);
        }
      } catch (error) {
        console.error('获取岗位列表失败：', error);
        this.$message.error('获取岗位列表失败，请稍后重试');
        return Promise.reject(error);
      } finally {
        this.postsLoading = false;
      }
    },

    // 处理岗位筛选变化
    async handlePostChange(type) {
      // 重置对应的数据列表，避免显示旧数据
      if (type === 'district') {
        this.districtRankData = [];
        await this.fetchDistrictRankData();
      } else if (type === 'personal') {
        this.personalRankData = [];
        await this.fetchPersonalRankData();
      }
    },

    // 切换数据周期
    changePeriod(period) {
      if (this.activePeriod === period) return;
      this.activePeriod = period;
      this.updateChartData();
    },

    // 更新图表数据
    updateChartData() {
      if (!this.chartInstance) return;

      const seriesData = this.activePeriod === 'sevenDays'
        ? this.barChartData.sevenDaysData
        : this.barChartData.monthData;

      this.chartInstance.setOption({
        series: [
          {
            data: seriesData
          }
        ]
      });
    },

    // 图表自适应
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    // 获取统计卡片数据
    async fetchStatsData() {
      this.statsLoading = true;
      try {
        const res = await req('post', '/home/getTotalCount', {});
        return res;
      } finally {
        this.statsLoading = false;
      }
    },

    // 获取图表数据
    async fetchChartData() {
      this.chartLoading = true;
      try {
        const res = await req('post', '/home/listDistrictActive', {});
        return res;
      } finally {
        this.chartLoading = false;
      }
    },

    // 获取区县排行数据（带岗位筛选）
    async fetchDistrictRankData() {
      this.districtRankLoading = true;
      try {
        const res = await req('post', '/score/getDistrictRank', {
          positionId: this.districtPost || ''
        });
        this.processDistrictRankResponse(res);
        return res;
      } catch (error) {
        console.error('获取区县排行数据失败：', error);
        this.$message.error('获取区县排行数据失败，请稍后重试');
        return Promise.reject(error);
      } finally {
        this.districtRankLoading = false;
      }
    },

    // 获取个人排行数据（带岗位筛选）
    async fetchPersonalRankData() {
      this.personalRankLoading = true;
      try {
        const res = await req('post', '/score/getPersonRank', {
          positionId: this.personalPost || ''
        });
        this.processPersonalRankResponse(res);
        return res;
      } catch (error) {
        console.error('获取个人排行数据失败：', error);
        this.$message.error('获取个人排行数据失败，请稍后重试');
        return Promise.reject(error);
      } finally {
        this.personalRankLoading = false;
      }
    },

    // 获取各区县人数数据
    async fetchDistrictPeopleData() {
      this.districtPeopleLoading = true;
      try {
        const res = await req('post', '/home/listDistrictUsers', {});
        return res;
      } finally {
        this.districtPeopleLoading = false;
      }
    },

    // 处理统计数据响应
    processStatsResponse(res) {
      if (res.result === 'success') {
        this.todayActiveUser = res.data.activeUserCount.todayActiveUsers;
        this.sevenDayActiveUser = res.data.activeUserCount.last7DaysActiveUsers;
        this.todayCertify = res.data.totalCount.certifiedCount;
        this.todayPk = res.data.totalCount.pkUsers;
      } else {
        this.$message.error(res.message || '获取统计数据失败');
      }
    },

    // 处理图表数据响应
    processChartResponse(res) {
      if (res.result === 'success') {
        const data = res.data || {};
        // 处理区县数据
        const districtArr = data.district ? res.data.district.split(',') : [];
        // 处理7天数据
        const sevenDaysCount = data.sevenDaysCount ? res.data.sevenDaysCount.split(',').map(Number) : [];
        // 处理月数据
        const monthCount = data.monthCount ? res.data.monthCount.split(',').map(Number) : [];

        this.barChartData.xAxisData = districtArr;
        this.barChartData.sevenDaysData = sevenDaysCount;
        this.barChartData.monthData = monthCount;
      } else {
        this.$message.error(res.message || '获取图表数据失败');
      }
    },

    // 处理区县排行响应
    processDistrictRankResponse(res) {
      if (res.result === 'success') {
        this.districtRankData = res.data || [];
      } else {
        this.$message.error(res.message || '获取区县排行数据失败');
      }
    },

    // 处理个人排行响应
    processPersonalRankResponse(res) {
      if (res.result === 'success') {
        this.personalRankData = res.data || [];
      } else {
        this.$message.error(res.message || '获取个人排行数据失败');
      }
    },

    // 处理各区县人数响应
    processDistrictPeopleResponse(res) {
      if (res.result === 'success') {
        this.districtPeopleData = res.data;
      } else {
        this.$message.error(res.message || '获取各区县人数数据失败');
      }
    },

    // 初始化柱状图
    initBarChart() {
      // 销毁已有实例
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }

      this.chartInstance = echarts.init(document.getElementById('districtBarChart'));

      // 自定义主题颜色
      const themeColor = '#4080FF';
      const seriesData = this.activePeriod === 'sevenDays'
        ? this.barChartData.sevenDaysData
        : this.barChartData.monthData;

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          padding: 10,
          textStyle: {
            fontSize: 12
          },
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              opacity: 0.1
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.barChartData.xAxisData,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#E5E5E5'
            }
          },
          axisLabel: {
            color: '#666',
            interval: 0, // 显示所有标签
            fontSize: 11,
            rotate: 0,
            margin: 5 // 缩小与柱子间距
          }
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#F0F0F0'
            }
          }
        },
        series: [
          {
            barCategoryGap: '20%',
            data: seriesData,
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                  { offset: 0, color: themeColor },
                  { offset: 1, color: '#6AA1FF' }
                ]
              ),
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#266BDF' },
                    { offset: 1, color: '#4080FF' }
                  ]
                )
              }
            },
            label: {
              show: true,
              position: 'top',
              color: '#333',
              fontSize: 12
            }
          }
        ]
      };

      this.chartInstance.setOption(option);
    },
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.stats-card {
  margin-bottom: 20px;
}
.card-item {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}
.card-item:hover {
  transform: translateY(-5px);
}
.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}
.card-value {
  font-size: 24px;
  color: #333;
  font-weight: bold;
}
.chart-box {
  margin-bottom: 20px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.chart-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 0;
  font-weight: bold;
}
.chart-controls {
  display: flex;
}
.list-row {
  margin-top: 20px;
}
.list-box {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 100%;
}
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.list-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 0;
  font-weight: bold;
}

/* 表格滚动样式 */
.table-scroll-container {
  overflow: hidden;
}
.ant-table-body {
  overflow-y: auto !important;
}
/* 隐藏表格底部边框，避免滚动时显示异常 */
.ant-table-footer, .ant-table-summary {
  border-top: none !important;
}
/* 优化滚动条样式 */
.ant-table-body::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.ant-table-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
.ant-table-body::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}
.ant-table-body::-webkit-scrollbar-thumb:hover {
  background: #aaa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .list-row a-col {
    margin-bottom: 20px;
  }
  .card-item {
    margin-bottom: 16px;
  }
  .chart-box {
    padding: 10px;
  }
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .chart-controls {
    margin-top: 10px;
    width: 100%;
    justify-content: space-between;
  }
  .list-box {
    padding: 10px;
  }
  .list-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .list-header .ant-select {
    margin-top: 8px;
    width: 100%;
  }
  /* 移动端调整表格高度 */
  .ant-table-scroll {
    :scroll="{ y: 220 }" !important;
  }
}
</style>
